#include "CSPI.h"

uint8 _SCK = 10;
uint8 _MOSI = 11;
uint8 _MISO = 12;
BOOL _HighFirst = True;
CPOL_enum _CPOL = CPOLH;
CPHA_enum _CPHA = CPHAH;

void Spi_Init(uint8 SCK, uint8 MOSI, uint8 MISO, BOOL HighFirst, CPOL_enum CPOL, CPHA_enum CPHA)
{

	_HighFirst = HighFirst;
	_CPOL = CPOL;
	_CPHA = CPHA;
	_SCK = SCK;
	_MOSI = MOSI;
	_MISO = MISO;

	pinMode(_SCK, OUTPUT);
	pinMode(_MOSI, OUTPUT);
	pinMode(_MISO, INPUT);
	digitalWrite(_SCK, _CPOL);


}


uint8 Spi_RWByte(uint8 data)
{
	uint8 res = 0;
	if (_HighFirst)
	{
		for (size_t i = 0x80; i > 0; i >>= 1)
		{
			digitalWrite(_SCK, _CPOL);

			if (data & i)
			{
				digitalWrite(_MOSI, HIGH);
			}
			else
			{
				digitalWrite(_MOSI, LOW);
			}

			digitalWrite(_SCK, !_CPOL);

			if (!_CPHA)
			{
				if (digitalRead(_MISO))
					res |= i;
			}
			digitalWrite(_SCK, _CPOL);
			if (_CPHA)
			{
				if (digitalRead(_MISO))
					res |= i;
			}
		}
	}
	else
	{
		for (size_t i = 0x01; i < 0x100; i <<= 1)
		{
			digitalWrite(_SCK, _CPOL);

			if (data & i)
			{
				digitalWrite(_MOSI, HIGH);
			}
			else
			{
				digitalWrite(_MOSI, LOW);
			}

			digitalWrite(_SCK, !_CPOL);

			if (!_CPHA)
			{
				if (digitalRead(_MISO))
					res |= i;
			}
			digitalWrite(_SCK, _CPOL);
			if (_CPHA)
			{
				if (digitalRead(_MISO))
					res |= i;
			}
		}
	}

	return res;
}